package com.yykt.myapp.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yykt.myapp.enums.ResultEnum;
import lombok.Data;

import java.io.Serializable;

@Data
public class JsonResult<T> implements Serializable {

    /**
     * 错误码.
     */
    private Integer code;

    /**
     * 提示信息.
     */
    private String msg;

    /**
     * 具体内容.
     */
    private T data;
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static JsonResult success(Object object) {
        JsonResult resultVO = new JsonResult();
        resultVO.setData(object);
        resultVO.setCode(200);
        resultVO.setMsg("成功");
        return resultVO;
    }

    public static JsonResult success() {
        return success(null);
    }

    /**
     * code 不等于 200 均为错误
     *
     * @param code
     * @param msg
     * @return
     */
    public static JsonResult error(Integer code, String msg) {
        JsonResult resultVO = new JsonResult();
        resultVO.setCode(code);
        resultVO.setMsg(msg);
        return resultVO;
    }

    /**
     * code 不等于 200 均为错误
     *
     * @param msg
     * @return
     */
    public static JsonResult error(String msg) {
        JsonResult resultVO = new JsonResult();
        resultVO.setCode(500); // 所有未知错误，都认为是500服务器错误
        resultVO.setMsg(msg);
        return resultVO;
    }

    public static JsonResult error(Object object) {
        JsonResult resultVO = new JsonResult();
        resultVO.setData(object);
        resultVO.setCode(500);
        resultVO.setMsg("异常");
        return resultVO;
    }

    public static JsonResult error(ResultEnum res) {
        JsonResult resultVO = new JsonResult();
        resultVO.setCode(res.getCode());
        resultVO.setMsg("异常");
        return resultVO;
    }
}
